package com.moyuxi.sound_of_the_forest.ui.compose

import androidx.activity.compose.BackHandler
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Info
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CardElevation
import androidx.compose.material3.DrawerState
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalDrawerSheet
import androidx.compose.material3.ModalNavigationDrawer
import androidx.compose.material3.NavigationDrawerItem
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.navigation.NavHostController
import com.moyuxi.sound_of_the_forest.R
import com.moyuxi.sound_of_the_forest.ui.route.AppRouter
import com.moyuxi.sound_of_the_forest.ui.route.MusicClassifyRouter
import com.moyuxi.sound_of_the_forest.ui.route.OtherClassifyRouter
import com.moyuxi.sound_of_the_forest.ui.route.RouteI
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch

/**
 * 封装侧边抽屉栏组件
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SideDrawerCompose(
    drawerState: DrawerState,
    scope: CoroutineScope,
    navigateToScreen: (RouteI) -> Unit,
    musicClassifyNC: NavHostController,
    content: @Composable () -> Unit
) {
    // 抽屉菜单点击回调方法，功能项被点击后默认执行关闭抽屉操作，在执行传入的回调方法。
    val closeMenuDrawer = { scope.launch { drawerState.close() } }
    // 导航前弹出 （单导航节点模式，底部导航栏）并关闭抽屉菜单。
    val navigateAndPopUpTo: (RouteI) -> Unit = { toRoute: RouteI ->
        closeMenuDrawer.invoke()
        if (toRoute.route != musicClassifyNC.currentDestination?.route) {
            musicClassifyNC.navigate(toRoute.route) {
                musicClassifyNC.currentDestination?.route?.let { popUpTo(it) { inclusive = true } }
                launchSingleTop = true
            }
        }
    }
    val navigateScreen: (RouteI) -> Unit = { toRoute: RouteI ->
        closeMenuDrawer.invoke()
        navigateToScreen(toRoute)
    }
    // 返回拦截：是否可关闭抽屉
    BackHandler(enabled = drawerState.isOpen) {
        closeMenuDrawer.invoke()
    }
    // 模态导航抽屉
    ModalNavigationDrawer(
        // 模态导航抽屉 - 抽屉菜单组件
        { SideDrawerMenuCompose(navigateAndPopUpTo, navigateScreen, musicClassifyNC) },
        drawerState = drawerState,
        gesturesEnabled = true,
        scrimColor = Color.Transparent,
        content = content,
    )
}

/**
 * 模态导航抽屉 - 抽屉菜单组件
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun SideDrawerMenuCompose(
    navigateAndPopUpTo: (RouteI) -> Unit,
    navigateToScreen: (RouteI) -> Unit,
    musicClassifyNC: NavHostController,
) {
    // 模态导航抽屉 - 菜单组件
    ModalDrawerSheet(modifier = Modifier.fillMaxWidth(0.45f)) {
        // 用作头部图片
        Image(
            painterResource(id = R.drawable.logo),
            "头图",
            Modifier
                .fillMaxWidth()
//                .background(Color.Transparent)
                .heightIn(150.dp, 300.dp),
            Alignment.Center,
            ContentScale.FillWidth,
        )
        // 菜单组 - 音乐分类组卡片
        GetCardItem {
            // 简化路由枚举
            val musicMCR = MusicClassifyRouter.MusicList
            val albumMCR = MusicClassifyRouter.AlbumList
            val artistMCR = MusicClassifyRouter.ArtistList
            // 菜单组内选择项
            var selectedItem by remember { mutableStateOf(musicMCR.name) }
            // 音乐类别内的导航监听  出现重复触发。
            musicClassifyNC.addOnDestinationChangedListener { _, navD, _ ->
                selectedItem = when (navD.route) {
                    musicMCR.route -> musicMCR.name
                    albumMCR.route -> albumMCR.name
                    artistMCR.route -> artistMCR.name
                    else -> ""
                }
            }
            // 音乐类别内子项
            GetDrawerItem(// 音乐项 歌曲
                musicMCR, Icons.Default.Info, selectedItem
            ) { navigateAndPopUpTo(musicMCR) }
            GetDrawerItem(// 音乐项 专辑
                albumMCR, Icons.Default.Info, selectedItem
            ) { navigateAndPopUpTo(albumMCR) }
            GetDrawerItem(// 音乐项 艺术家
                artistMCR, Icons.Default.Info, selectedItem
            ) { navigateAndPopUpTo(artistMCR) }
        }
        // 菜单组 - 其它分类组卡片
        GetCardItem {
            GetDrawerItem(// 其它项 扫描歌曲
                OtherClassifyRouter.ScanMusic, Icons.Default.Info
            ) {
                navigateToScreen(AppRouter.ScanMusic)
            }
            GetDrawerItem(// 其它项 关于我
                OtherClassifyRouter.AboutMe, Icons.Default.Info
            ) {
                navigateToScreen(AppRouter.AboutMeScreen)
            }
        }
    }
}

/**
 * 获取抽屉内子项组件
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun GetDrawerItem(
    label: RouteI,
    imageVector: ImageVector,
    selectedItem: String? = null,
    onClick: () -> Unit,
) {
    // 抽屉项目组件
    NavigationDrawerItem(
        { Text(label.name) },
        label.name == selectedItem,
        onClick,
        icon = { Icon(imageVector, label.name) },
        shape = MaterialTheme.shapes.large,
//        colors = NavigationDrawerItemDefaults.colors(MaterialTheme.colorScheme.secondaryContainer,Color.Transparent)
    )
}

/**
 * 获取抽屉菜单组卡片组件
 */
@Composable
private fun GetCardItem(
    modifier: Modifier = Modifier
        .fillMaxWidth()
        .padding(10.dp),
    shape: Shape = MaterialTheme.shapes.large,
//    colors: CardColors = CardDefaults.cardColors(MaterialTheme.colorScheme.background),
    elevation: CardElevation = CardDefaults.cardElevation(5.dp),
    border: BorderStroke? = null,
    content: @Composable (ColumnScope.() -> Unit)
) {
    // 卡片组件
    Card(
        modifier = modifier,
        shape = shape,
        elevation = elevation,
        border = border,
        content = content
    )
}
//
//@Preview(name = "抽屉内容 - 日间")
//@Preview(name = "抽屉内容 - 夜间", uiMode = Configuration.UI_MODE_NIGHT_YES)
//@Composable
//@OptIn(ExperimentalMaterial3Api::class)
//fun DrawerPreview() {
//    val drawerState = rememberDrawerState(DrawerValue.Open)
//    val scope = rememberCoroutineScope()
//    val navController = rememberNavController()
//    val musicClassifyNavController = rememberNavController()
//    SideDrawerCompose(
//        drawerState,
//        scope,
//        navigateToScreen = { navController },
//        musicClassifyNC = musicClassifyNavController
//    ) {
//        MusicListFrameCompose(navController, viewModel(),showSheet)
//    }
//}